import requests
import json
import sys
from CAAi3dxClient import CAAi3dxClient


class CAAi3dxGetWebServicesClient:
    def __init__(self, client):
        self._client = client

    def run(self, app_path) -> str:
        # - Redirect sys.stdout (PrintStream equivalent)
        output = None
        old_output = sys.stdout
        output_dir = self._client.get_out()
        print("#RESPONSE BODY", output_dir)

        # Uncomment if output redirection is needed
        # if output_dir:
        #     output = open(output_dir + "api_get_ws.traces", "w", encoding=CAAi3dxClient.ENCODING)
        #     sys.stdout = output

        # - Build web service url
        ws_url = f"{self._client.get_3d_space_server()}{app_path}"

        # - Send query and catch response
        response = self._client.get_url_loader().load_url(ws_url, "GET", None, None)
        res_str = response.decode(CAAi3dxClient.ENCODING)

        print("response=====")
        print(res_str)

        # Display the response in the output file
        # if response:
        #     print("#RESPONSE BODY")
        #     print("#--------------------")
        #     response_type = self._client.get_url_loader().content_type()
        #     print("response_type=====", response_type)
        #     if "json" in response_type:
        #         print(CAAi3dxClient.get_json(response))
        #     else:
        #         print(f"Unhandled response Content-Type={response_type}")

        # If error, raise an exception with the backend error code
        if self._client.get_url_loader().response_code() != 200:
            http_code = self._client.get_url_loader().response_code()
            http_msg = self._client.get_url_loader().response_message()
            raise Exception(f"WS Response Code={http_code}- {http_msg}")

        return res_str

        # - Restore sys.stdout
        # if output_dir and output:
        #     output.flush()
        #     output.close()
        #     sys.stdout = old_output
